//
//  LZFBaseVC.m
//  LZFBuDieJie
//
//  Created by 梁梓烽 on 16/7/4.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "LZFBaseVC.h"
#import "LZFAllVC.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <SVProgressHUD.h>
#import "LZFTopicItem.h"
#import "LZFTopicCell.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "LZFDIYHeader.h"
#import "LZFDIYHeaderTwo.h"
#import "LZFDIYAutoFooter.h"
#import "LZFHttpSessionManager.h"
#import "LZFCommentController.h"
#import "LZFNavgationController.h"
#import "LZFNewController.h"

@interface LZFBaseVC ()
//@property(nonatomic,weak)UILabel *updateLabel;
//@property(nonatomic,weak)UILabel *loadLabel;
//@property(nonatomic,assign,getter=isHeaderFresh)BOOL headerFresh;
//@property(nonatomic,assign,getter=isFooterFresh)BOOL footerFresh;
@property(nonatomic,weak)LZFHttpSessionManager *manager;
@property(nonatomic,strong)NSString *maxtime;
@property(nonatomic,strong)NSMutableArray *topicItemArray;

//帖子类型
-(NSInteger)type;
//精华or新帖
-(NSString *)aParam;

@end
@interface LZFBaseVC ()

@end

@implementation LZFBaseVC
static NSString  *const ID=@"cell";
#pragma mark AFHTTPSessionManager懒加载
-(AFHTTPSessionManager *)manager
{
    if (_manager==nil) {
        _manager=[LZFHttpSessionManager manager];
    }
    return  _manager;
}

#pragma mark viewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
   
    //设置tableview
    [self setUpTableView];
    
    //设置刷新控件
    [self setUpFresh];
    
    //程序一开始就开始下拉刷新
    //[self beginHeaderFresh];
    [self.tableView.mj_header beginRefreshing];
    
    //注册监听
    [self setUpNote];
    
    
  
}

#pragma mark 初始化设置
-(void)setUpTableView
{
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZFTopicCell class]) bundle:nil] forCellReuseIdentifier:ID];
    
    //设置tableview全屏穿透
    self.tableView.contentInset=UIEdgeInsetsMake(LZFNavMaxY+LZFTitleViewH, 0, LZFTabBarMaxH, 0);
    self.tableView.scrollIndicatorInsets=self.tableView.contentInset;
    
    //设置tableview背景颜色
    self.view.backgroundColor=LZFGlobalColor;
    
    //取消tableview的分割线
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;//取消分割线
}


-(void)setUpNote
{
    
    //注册监听 tabbarbutton重复点击的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tabBarButtonDidRepeatClicked) name:LZFTabBarButtonDidRepeatClickedNotification object:nil];
    
    //注册监听  titlebutton重复点击的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(titleButtonDidClicked) name:LZFTitleButtonDidClickedNotification object:nil];
    
}


//设置刷新控件
-(void)setUpFresh
{
    /*
     //下拉刷新label
     UILabel *updateLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, -50, screenW, 50)];
     self.updateLabel=updateLabel;
     updateLabel.backgroundColor=[UIColor redColor];
     updateLabel.text=@"下拉可刷新";
     updateLabel.textAlignment=NSTextAlignmentCenter;
     //updateLabel.frame=;
     [self.tableView addSubview:updateLabel];
     
     //上拉动刷新label
     UILabel *loadLabel=[[UILabel alloc]init];
     loadLabel.backgroundColor=[UIColor redColor];
     loadLabel.text=@"上拉加载更多数据....";
     loadLabel.textAlignment=NSTextAlignmentCenter;
     loadLabel.frame=CGRectMake(0, 0, 0, 35);
     self.loadLabel=loadLabel;
     self.tableView.tableFooterView=loadLabel;
     */
    
    //设置头部刷新控件
    [self setLZFUpdateNormalLabel];
    
    
    //设置尾部刷新控件
    [self setLZFLoadNormalLabel];
    
    
    
    //广告label
    UILabel *adLabel=[[UILabel alloc]init];
    adLabel.backgroundColor=[UIColor grayColor];
    adLabel.text=@"广告......";
    adLabel.textAlignment=NSTextAlignmentCenter;
    adLabel.frame=CGRectMake(0, 0, 0, 35);
    self.tableView.tableHeaderView=adLabel;
    
}

#pragma mark 通知触发
-(void)titleButtonDidClicked
{
    
    //限制选中的是精华控制器才可以通过
    if (self.view.window==nil) return;
    
    //限制选中的是全部模块的才可以通过
    UIScrollView *scrollView=( UIScrollView *)self.view;
    if (scrollView.scrollsToTop==NO)return;
    
    //开始下拉更新数据
   // [self beginHeaderFresh];
    [self.tableView.mj_header beginRefreshing];
    
}


-(void)tabBarButtonDidRepeatClicked
{
    [self titleButtonDidClicked];
}


#pragma mark 移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark mjrefresh mj_header的各种用法

//设置普通的头部刷新控件
-(void)setLZFUpdateNormalLabel
{
    MJRefreshNormalHeader *header =[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewToPic)];
    self.tableView.mj_header=header;
    
    header.stateLabel.hidden=YES;
    header.lastUpdatedTimeLabel.hidden=YES;
    
    
    // Set title
    //    [header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle];
    //    [header setTitle:@"Release to refresh" forState:MJRefreshStatePulling];
    //    [header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing];
    
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"释放立即刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"正在刷新..." forState:MJRefreshStateRefreshing];
    
    //    // Set font
    //    header.stateLabel.font = [UIFont systemFontOfSize:15];
    //    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    //
    //    // Set textColor
    //    header.stateLabel.textColor = [UIColor redColor];
    //    header.lastUpdatedTimeLabel.textColor = [UIColor blueColor];
}

//设置带动画的头部刷新控件
-(void)setLZFUpdateGifLabel
{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewToPic)];
    
    
    // 设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_anim__000%zd", i]];
        [idleImages addObject:image];
    }
   
    
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=3; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_loading_0%zd", i]];
        [refreshingImages addObject:image];
    }
  
    // 设置正在刷新状态的动画图片
   
    [header setImages:idleImages forState:MJRefreshStateIdle];
  
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
   
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
     self.tableView.mj_header=header;
    
}

//设置自定义的头部刷新控件
-(void)setLZFUpdateDIYLabel
{
    self.tableView.mj_header=[LZFDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewToPic)];
}
//设置自定义的头部刷新控件2
-(void)setLZFUpdateDIYLabel2
{
    self.tableView.mj_header=[LZFDIYHeaderTwo headerWithRefreshingTarget:self refreshingAction:@selector(loadNewToPic)];
}


#pragma  mark mjrefresh mj_footer 的各种用法

//设置普通的尾部刷新控件
-(void)setLZFLoadNormalLabel
{
    MJRefreshAutoNormalFooter *footer =[MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    
    // Set title
    [footer setTitle:@"Click or drag up to refresh" forState:MJRefreshStateIdle];
    [footer setTitle:@"Loading more ..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"No more data" forState:MJRefreshStateNoMoreData];
    
    // Set font
    footer.stateLabel.font = [UIFont systemFontOfSize:17];
    
    // Set textColor
    footer.stateLabel.textColor = [UIColor blueColor];
    
    //hiddle title
    //footer.refreshingTitleHidden=YES;
    
    self.tableView.mj_footer=footer;
}

//带动画的尾部刷新
-(void)setLZFLoadGifLabel
{
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    //footer.refreshingTitleHidden = YES;
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=3; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"dropdown_loading_0%zd", i]];
        [refreshingImages addObject:image];
    }

    [footer setImages:refreshingImages forState:MJRefreshStateRefreshing];

    self.tableView.mj_footer = footer;
}


//自动回弹的上拉
-(void)setLZFLoadAumaticBackLabel
{
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    
}


//DIY的上拉刷新
-(void)setLZFLoadDIYLabel
{
    self.tableView.mj_footer=[LZFDIYAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
}

#pragma mark  scrollviewdelegate

//监听滚动行为
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //在滚动过程中清除缓存
    [[SDImageCache sharedImageCache]clearMemory];
}


#pragma mark 封装请求参数
//帖子类型
-(NSInteger)type
{
    return LZFTopicTypePic;
}

//精华or新帖
-(NSString *)aParam
{
    if ([self.parentViewController isKindOfClass:[LZFNewController class]]) {
        return @"newlist";
    }
    
    return @"list";
}



#pragma mark 发送网络请求,加载数据
//加载新的数据
-(void)loadNewToPic
{
    //每次发送请求时,都停止之前的task
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //http://api.budejie.com/api/api_open.php?a=list&c=data
    NSMutableDictionary *dic=[NSMutableDictionary new];
    dic[@"a"]=self.aParam;
    dic[@"c"]=@"data";
    dic[@"type"]=@([self type]);
    
    WeakSelf
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
       // LZFAFNWriteToPlist(@"dd")
        //获取maxtime,拿到上次请求数据的maxtime.用于下次发送请求发送给服务器,返回下一页的数据
        NSString *maxtime = responseObject[@"info"][@"maxtime"];
        weakSelf.maxtime=maxtime;
        
        NSMutableArray *array=responseObject[@"list"];
        
        //字典数组转模型数组
        weakSelf.topicItemArray=[LZFTopicItem mj_objectArrayWithKeyValuesArray:array];
        
        //刷新tableview
        [weakSelf.tableView reloadData];
        
        //结束头部刷新
       // [self endHeaderFresh];
        [weakSelf.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //结束头部刷新
       // [self endHeaderFresh];
        [weakSelf.tableView.mj_header endRefreshing];
        
        // 如果是因为取消任务来到failure这个block, 就直接返回, 不需要提醒错误信息
        if (error.code == NSURLErrorCancelled) return;
        
        // 请求失败的提醒
        [SVProgressHUD showErrorWithStatus:@"网络繁忙,请稍后再试!"];
        
    }];
    
}

//上拉加载更多的数据
-(void)loadMoreTopic
{
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    NSMutableDictionary *dic=[NSMutableDictionary new];
    dic[@"a"]=self.aParam;
    dic[@"c"]=@"data";
    dic[@"type"]=@([self type]);
    dic[@"maxtime"]=self.maxtime;
    
    WeakSelf
    [self.manager GET:@"http://api.budejie.com/api/api_open.php"parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        //获取maxtime,拿到上次请求数据的maxtime.用于下次发送请求发送给服务器,返回下一页的数据
        NSString *maxtime = responseObject[@"info"][@"maxtime"];
        weakSelf.maxtime=maxtime;
        
        NSMutableArray *array=responseObject[@"list"];
        
        //字典数组转模型数组
        NSMutableArray *topicsArray=[LZFTopicItem mj_objectArrayWithKeyValuesArray:array];
        
        //将新的数据加到
        [weakSelf.topicItemArray addObjectsFromArray:topicsArray];  //注意这里是追加到数据,而不是覆盖原来的数组
        
        //刷新表格
        [weakSelf.tableView reloadData];
        
        //结束尾部刷新
       // [self endFooterFresh];
        [weakSelf.tableView.mj_footer endRefreshing];
        //[self.tableView.mj_footer endRefreshingWithNoMoreData];  //没有更多的数据,已经全部加载完数据
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
       // [self endFooterFresh];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}




#pragma mark  tableviewdatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //没数据的话,tablefooterview不用显示
    self.tableView.mj_footer.hidden=(self.topicItemArray.count==0);
    return self.topicItemArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZFTopicItem *topicItem=self.topicItemArray[indexPath.row];
    //LZFLog(@"%@",topicItem.topComment);
    LZFTopicCell *topicCell=[tableView dequeueReusableCellWithIdentifier:ID];
    topicCell.topicItem=topicItem;
    return topicCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZFTopicItem *topicItem=self.topicItemArray[indexPath.row];
    return topicItem.rowHeight;
}


#pragma mark tableviewdelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZFTopicItem *topic = self.topicItemArray[indexPath.row];
    LZFCommentController *commentVC=[[LZFCommentController alloc]init];
    commentVC.topicItem=topic;
  
    [self.navigationController pushViewController:commentVC animated:YES];

}


@end
